package ext.tianma.part;

import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.fc.QueryResult;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.util.WTException;
import ext.com.core.CoreUtil;
import ext.com.iba.IBASearchUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.exception.TmException;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.IbaAttributeUtil;

/**
 * 设置并生成虚拟偏光片的Mark
 * 
 * @author xuge_ning
 * 
 */
public class PartMarkUtil {

	public final static int MARK_LENGTH = 34;

	public static String MARK_STR1 = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";

	public static String MARK_STR2 = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

	public static String VIEW_I10 = "I10";
	public static String VIEW_I13 = "I13";

	public static Logger logger = Logger
			.getLogger(PartMarkUtil.class.getName());

	/**
	 * 设置Mark
	 * version 2。0
	 * @param part
	 * @throws TmException
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void setPartMark(Object pbo, WTPart POLPart)
			throws TmException {
		if (pbo != null && pbo instanceof WTPart) {
			WTPart part = (WTPart) pbo;
			try {
				part = CoreUtil.getWTPartByMasterAndView(
						(WTPartMaster) part.getMaster(), "Design");
			} catch (WTException e) {
				e.printStackTrace();
			}
			// 获取料号生效地，I10、I13不需要生成mark
			List<String> valueList = IbaAttributeUtil.getAttributeValues(part,
					"partNumberEffectiveSite");
			if (valueList.isEmpty() || valueList.contains(VIEW_I10)
					|| valueList.contains(VIEW_I13)) {
				return;
			}
			// 如果为上片
			if (TMTypeUtil.isTopPolarizer(part)) {
				setPolarizerMark(part);
				// 如果为下片
			} else if (TMTypeUtil.isBotPolarizer(part)) {
				String isBothNewPolarizer = IbaAttributeUtil.getAttributeValue(
						part, "isBothNewPolarizer");
				if (StringUtils.isNotBlank(isBothNewPolarizer)) {
					// 上下均为新增
					if ("是".equals(isBothNewPolarizer)) {
						setFollowMark(part, POLPart);
					} else {
						// 生成新的mark值。
						setPolarizerMark(part);
					}
				}
			}
		}
	}

	/**
	 * 设置Mark
	 * version1.0
	 * @param part
	 * @throws TmException
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void setPartMark(Object pbo) throws RemoteException,
			WTException {
		if ((pbo != null) && ((pbo instanceof WTPart))) {
			WTPart part = (WTPart) pbo;
			part = CoreUtil.getWTPartByMasterAndView(
					(WTPartMaster) part.getMaster(), "Design");

			if (TMTypeUtil.isTopPolarizer(part)) {
				setPolarizerMark(part);
			} else if (TMTypeUtil.isBotPolarizer(part)) {
				String isBothNewPolarizer = (String) IBAUtil.getIBAValue(part,
						"isBothNewPolarizer");
				if ((isBothNewPolarizer != null)
						&& (!"".equals(isBothNewPolarizer)))
					if ("是".equals(isBothNewPolarizer)) {
						setFollowMark(part);
					} else
						setPolarizerMark(part);
			}
		}
	}
	/**
	 * version 1.0 旧版本
	 * @param part
	 * @throws RemoteException
	 * @throws WTException
	 */
	private static void setFollowMark(WTPart part) throws RemoteException,
			WTException {
		Object mtlNumofPOLTop = IBAUtil.getIBAValue(part, "MtlNumofPOLTop");
		if (mtlNumofPOLTop != null) {
			String str = (String) mtlNumofPOLTop;
			if (!str.trim().isEmpty()) {
				str = str.trim();
				WTPart topWtPart = CoreUtil.getWTPartByNumberAndView(str,
						"Design");
				if (topWtPart != null) {
					String mark = (String) IBAUtil.getIBAValue(topWtPart,
							"partMark");
					if ((mark != null) && (!mark.trim().isEmpty()))
						IBAUtil.forceSetIBAValue(part, "partMark", mark);
				} else {
					throw new WTException("上偏光片对应的料号不存在，请重新填写");
				}
			}
		} else {
			throw new WTException("上偏光片对应的料号不存在，请重新填写");
		}
	}
	
	/**
	 * 写回对应偏光片料号
	 * version 1.0 旧版本
	 * @param dPart
	 */
	public static void writeBackPOLNum(WTPart dPart) {
		try {
			dPart = CoreUtil.getWTPartByMasterAndView(
					(WTPartMaster) dPart.getMaster(), "Design");
			if (TMTypeUtil.isBotPolarizer(dPart)) {
				Object MtlNumofPOLTopNum = IBAUtil.getIBAValue(dPart,
						"MtlNumofPOLTop");
				if (MtlNumofPOLTopNum != null) {
					String MtlNumofPOLTop = (String) MtlNumofPOLTopNum;
					if ((MtlNumofPOLTop != null) && (!MtlNumofPOLTop.trim().isEmpty())) {
						WTPart topWtPart = CoreUtil.getWTPartByNumberAndView(MtlNumofPOLTop, "Design");
						if (topWtPart != null) {
							topWtPart = (WTPart) CoreUtil.checkoutObject(topWtPart);
							IBAUtil.forceSetIBAValue(topWtPart,"MtlNumofPOLBtn", dPart.getNumber());
							CoreUtil.checkinObject(topWtPart, "写回对应下偏光片的料号");
						}
					}
				}
			} else if (TMTypeUtil.isTopPolarizer(dPart)) {
				String MtlNumofPOLBtn = (String) IBAUtil.getIBAValue(dPart,"MtlNumofPOLBtn");
				String isBothNewPolarizer = (String) IBAUtil.getIBAValue(dPart,"isBothNewPolarizer");
				if (("否".equals(isBothNewPolarizer)) && (MtlNumofPOLBtn != null)	&& (!MtlNumofPOLBtn.trim().isEmpty())) {
					WTPart botWtPart = CoreUtil.getWTPartByNumberAndView(MtlNumofPOLBtn, "Design");
					if (botWtPart != null) {
						botWtPart = (WTPart) CoreUtil.checkoutObject(botWtPart);
						IBAUtil.forceSetIBAValue(botWtPart, "MtlNumofPOLTop",dPart.getNumber());
						CoreUtil.checkinObject(botWtPart, "写回对应上偏光片的料号");
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置虚拟偏光片的Mark,随机生成
	 * 
	 * @param part
	 * @throws WTException
	 */

	private static String setRandomBySize(String size, String firstValue) {
		String partMark = "";
		boolean flag = false;
		do {
			flag = false;
			StringBuffer mark = new StringBuffer();
			Random random = new Random();
			for (int i = 0; i < 2; i++) {
				// 生成随机数
				int number = random.nextInt(MARK_STR1.length());
				mark.append(MARK_STR1.charAt(number));
			}
			partMark = firstValue + mark.toString();
			Hashtable ibaValues = new Hashtable();
			ibaValues.put("partSize", size);
			ibaValues.put("partMark", partMark);
			ibaValues.put("partEName", "Polarizer");
			QueryResult qr = null;
			try {
				qr = IBASearchUtil.queryIBAHolder(wt.part.WTPart.class,
						ibaValues);
			} catch (WTException e) {
				e.printStackTrace();
			}
			while (qr.hasMoreElements()) {
				flag = true;
				WTPart part = (WTPart) qr.nextElement();
				logger.info("已存在相同mark值的物料编码:" + part.getNumber());
			}
		} while (flag);
		return partMark;
	}

	/**
	 * 设置偏光片的Mark,相同尺寸的mark值要不相同。
	 */

	private static void setPolarizerMark(WTPart part) {
		String firstValue = "";
		String mark = "";
		String size = IbaAttributeUtil.getAttributeValue(part, "partSize");
		// 根据厂商获得第一位,获取partSupplier,获取的值格式为“manufacturer。A”
		String manufacturer = IbaAttributeUtil.getAttributeValue(part,
				"partSupplier");
		if (StringUtils.isNotBlank(size)
				&& StringUtils.isNotBlank(manufacturer)) {

			firstValue = manufacturer.substring(manufacturer.indexOf('.') + 1);
			// 根據規則,生成mark值
			mark = setRandomBySize(size, firstValue);
			logger.info("partNumber :" + part.getNumber()  + ",Mark:" + mark);
			if (StringUtils.isNotBlank(mark))
				try {
					IBAUtil.forceSetIBAValue(part, "partMark", mark);
				} catch (WTException e) {
					e.printStackTrace();
				}

		}
	}

	private static void setFollowMark(WTPart part, WTPart POLPart)
			throws TmException {
		try {
			POLPart = CoreUtil.getWTPartByMasterAndView(
					(WTPartMaster) POLPart.getMaster(), "Design");
		} catch (WTException e1) {
			e1.printStackTrace();
		}
		if (POLPart != null) {
			String POLPartNumber = POLPart.getNumber();
			if (StringUtils.startsWith(POLPartNumber, "00000")) {
				throw new TmException("上偏光片对应的物料的mark值不存在");
			}
			String mark = IbaAttributeUtil.getAttributeValue(POLPart,
					"partMark");
			if (StringUtils.isNotBlank(mark)) {
				try {
					IBAUtil.forceSetIBAValue(part, "partMark", mark);
				} catch (WTException e) {
					e.printStackTrace();
				}
			}
		} else {
			throw new TmException("上偏光片对应的物料不存在，请重新填写");
		}
	}

	// 写回对应偏光片料号的操作
	public static void writeBackPOLNum(WTPart dPart, WTPart POLPart)
			throws TmException {

		try {
			// 获取料号生效地，I10、I13不需要生成mark
			List<String> valueList = IbaAttributeUtil.getAttributeValues(dPart,
					"partNumberEffectiveSite");
			if (valueList.isEmpty() || valueList.contains(VIEW_I10)
					|| valueList.contains(VIEW_I13) || POLPart == null) {
				return;
			}
			POLPart = CoreUtil.getWTPartByMasterAndView(
					(WTPartMaster) POLPart.getMaster(), "Design");
			dPart = CoreUtil.getWTPartByMasterAndView(
					(WTPartMaster) dPart.getMaster(), "Design");
			// 检出零部件
			POLPart = (WTPart) CoreUtil.checkoutObject(POLPart);
			if (TMTypeUtil.isBotPolarizer(dPart)) {
				IBAUtil.forceSetIBAValue(POLPart, "MtlNumofPOLBtn",
						dPart.getNumber());
				IBAUtil.forceSetIBAValue(dPart, "MtlNumofPOLTop",
						POLPart.getNumber());
			} else if (TMTypeUtil.isTopPolarizer(dPart)) {
				IBAUtil.forceSetIBAValue(POLPart, "MtlNumofPOLTop",
						dPart.getNumber());
				IBAUtil.forceSetIBAValue(dPart, "MtlNumofPOLBtn",
						POLPart.getNumber());
			}
			// 检入部件,触发监听器同步其他视图的iba属性
			CoreUtil.checkinObject(POLPart, "写回对应偏光片的料号");
		} catch (WTException e) {
			e.printStackTrace();
		}

	}

	

}
